from flask import Flask
from flask import request
import json
from train import trainMachineState
import config as config
import pickle
import os
import logging
import featureextraction
import FEthread
import feature.PCA as PCA
import numpy as np
import pandas as pd
import feature.Sigma as Sigma
import feature.ABOD as ABOD
import feature.Box as Box
import feature.Cluster as Cluster
import feature.COF as COF
import feature.Histogram as Histogram
import feature.iForest as iForest
import feature.KNN as KNN
import feature.LOF as LOF
import feature.MCD as MCD
import feature.HGPCA as HGPCA
import feature.SVM as SVM
import feature.ZScore as ZScore
import feature.D_CNN as D_CNN
# import feature.GRU as GRU
import nankai.GRU as GRU
import feature.SVR as SVR
import feature.Poly as Poly
import feature.Grey_model as Grey_model
from feature.D_CNN import CNNnetwork
from feature.D_CNN import data_process as D_CNN_data_process
# from feature.GRU import Config
from nankai.GRU import Config
# from feature.GRU import data_process as GRU_data_process
from nankai.GRU import data_process as GRU_data_process
from feature.SVR import data_process as SVR_data_process
from feature.Poly import data_process as Poly_data_process
from feature.Grey_model import data_process as Grey_model_data_process
from nankai.F_test import f_test as f_test
from nankai.T_test import t_test as t_test
from nankai.wilcoxon_test import wilcoxon2 as wilcoxon2
from nankai.Maha_dist import MahalanobisDistance as MahalanobisDistance
from nankai.SPRT_algorithm import sbtr_calculte as sbtr_calculte
from nankai.RLS import RecursiveLS
from nankai.RLS import rls_calculte as rls_calculte
from yanjiuyuan.temperature import temperature_rise_route
from yanjiuyuan.fuzzy_safe import fuzzy_safe_route
from yanjiuyuan.deviation_calculation import deviation_calculation_route
from yanjiuyuan.correlation_test import correlation_test_route
from yanjiuyuan.normal_distribution_test import normal_distribution_test_route

#日志设置
log_name = 'platform_flask.log'
log_path = os.path.join(os.getcwd(), 'log', log_name)
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file = logging.FileHandler(filename=log_path)
file_format = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s",
                                datefmt='%Y-%m-%d %H:%M:%S')
file.setFormatter(file_format)
logging.getLogger().addHandler(file)


app = Flask(__name__)
#
if (config.server_mode == 0):
    _gb_machinestate = trainMachineState()


    @app.route('/getWaitTime', methods=['POST'])
    def getWaitTime():
        result = _gb_machinestate.getWaitTime()
        return json.dumps(result)


    @app.route('/getMachineStatus', methods=['POST'])
    def getMachineStatus():
        result = _gb_machinestate.getMachineStatus()
        return json.dumps(result)


    @app.route('/addTask', methods=['POST'])
    def addTask():
        data = request.get_data()
        json_data = json.loads(data.decode("utf-8"))
        logging.info("parameter1:" + str(json_data))
        print("json_data\n", json_data)
        result = _gb_machinestate.addTask(json_data)
        _gb_machinestate.startAllTaskList(json_data)
        logging.info('result1:' + json.dumps(result))
        return json.dumps(result)


    @app.route('/stopTask', methods=['POST'])
    def stopTask():
        data = request.get_data()
        json_data = json.loads(data.decode("utf-8"))
        logging.info("parameter1:" + str(json_data))
        result = _gb_machinestate.stopTask(json_data)
        logging.info('result1:' + json.dumps(result))
        return json.dumps(result)


    @app.route('/getTaskList', methods=['POST'])
    def getTaskList():
        result = _gb_machinestate.getTaskList()
        logging.info('result1:' + json.dumps(result))
        return json.dumps(result)


    @app.route('/addFETask', methods=['POST'])
    def addFETask():
        myresponse = {}
        myresponse['ret'] = 0
        myresponse['msg'] = config.FE_Msg_Add_0

        #解析json参数
        data = request.get_data()
        json_data = json.loads(data.decode("utf-8"))

        #调用特征工程
        if featureextraction.check_param_FE(json_data):
            try:
                FEthread.myThread(json_data).start()
                return json.dumps(myresponse, ensure_ascii=True)
            except Exception as e:
                myresponse['ret'] = 1
                myresponse['msg'] = config.FE_Msg_Add_1
                return json.dumps(myresponse, ensure_ascii=True)
        else:
            myresponse['ret'] = 1
            myresponse['msg'] = config.FE_Msg_Add_1
            return json.dumps(myresponse, ensure_ascii=True)

    # 主成分分析算法接口调用
    @app.route('/pca', methods=['POST'])
    def pca():
        data = request.get_data()
        json_data = json.loads(data.decode("utf-8"))
        data = np.array(json_data['dataArr'])
        cum_var = float(json_data['cum_var'])
        # print("data:", data)
        # print("cum_var:", cum_var)
        p = PCA.PCA(data)
        proj_matrix, var_exp, X_pca, vectors = p.principal_comps(threshold=cum_var)
        # proj_matrix, var_exp, X_pca, vectors = p.principal_comps(threshold=0.95)
        # proj_matrix, var_exp, X_pca = pcaUtils.pca_analysis(data, cum_var)
        # ret 返回成功标识
        result = {'ret': 0, 'proj_matrix': proj_matrix.tolist(), 'var_exp': var_exp.tolist(), 'X_pca': X_pca.tolist()}
        # print(json.dumps(result))
        return json.dumps(result)

    # 华工高校算法通用调用接口
    @app.route('/testAlgo', methods=['POST'])
    def testAlgo():
        data = request.get_data()
        json_data = json.loads(data.decode("utf-8"))
        data_np = np.array(json_data['dataArr']) # 当前算法对应的测试数据集
        data_df = pd.DataFrame(data_np)
        ag_data = []
        algo_name = str(json_data['algoName']) # 根据算法名称调用对应处理算法
        testFileUrl = str(json_data['testFileUrl']) # 当前算法对应的数据测试文件
        # 华工故障诊断算法
        logging.info(algo_name +'算法调用，文件地址：' + testFileUrl)
        if algo_name == "Sigma":
            ag_data = Sigma.three_sigma_route(data_df, testFileUrl)
        elif algo_name == "ABOD":
            ag_data = ABOD.abod_anormal_detect(data_df, testFileUrl)
        elif algo_name == "Box":
            ag_data = Box.box_plot_route(data_df, testFileUrl)
        elif algo_name == "Cluster":
            ag_data = Cluster.cluster_anormal_detect(data_df, testFileUrl)
        elif algo_name == "COF":
            ag_data = COF.cof_anormal_detect(data_df, testFileUrl)
        elif algo_name == "Histogram":
            ag_data = Histogram.histogram_anormal_detect(data_df, testFileUrl)
        elif algo_name == "iForest":
            ag_data = iForest.iforest_anormal_detect(data_df, testFileUrl)
        elif algo_name == "KNN":
            ag_data = KNN.knn_anormal_detect(data_df, testFileUrl)
        elif algo_name == "LOF":
            ag_data = LOF.lof_anormal_detect(data_df, testFileUrl)
        elif algo_name == "MCD":
            ag_data = MCD.mcd_anormal_detect(data_df, testFileUrl)
        elif algo_name == "HGPCA":
            ag_data = HGPCA.pca_anormal_detect(data_df, testFileUrl)
        elif algo_name == "SVM":
            ag_data = SVM.svm_anormal_detect(data_df, testFileUrl)
        elif algo_name == "ZScore":
            ag_data = ZScore.z_score_route(data_df, testFileUrl)
        # 华工故障预测算法
        elif algo_name == "D_CNN":
            ag_data = D_CNN_data_process(data_df, testFileUrl)
        elif algo_name == "GRU":
            ag_data = GRU_data_process(data_df, testFileUrl)
        elif algo_name == "SVR":
            ag_data = SVR_data_process(data_df, testFileUrl)
        elif algo_name == "Poly":
            ag_data = Poly_data_process(data_df, testFileUrl)
        elif algo_name == "Grey_model":
            ag_data = Grey_model_data_process(data_df, testFileUrl)
        # 南开大学故障检测算法
        elif algo_name == "F_test":
            ag_data = f_test(data_df, testFileUrl)
        elif algo_name == "T_test":
            ag_data = t_test(data_df, testFileUrl)
        elif algo_name == "wilcoxon_test":
            ag_data = wilcoxon2(data_df, testFileUrl)
        elif algo_name == "Maha_dist":
            Maha_model = MahalanobisDistance(data=data_df, url=testFileUrl)
            ag_data = Maha_model.allMahaDist()
        elif algo_name == "SPRT_algorithm":
            ag_data = sbtr_calculte(data_df, testFileUrl)
        elif algo_name == "RLS":
            # ag_data = rls_calculte(data_df, testFileUrl)
            ag_data = rls_calculte(testFileUrl, 'Sheet1', 'Sheet2')
        # 杭州研究院故障预测算法
        elif algo_name == "temperature":
            ag_data = temperature_rise_route(testFileUrl)
        elif algo_name == "de_calculation":
            ag_data = deviation_calculation_route(testFileUrl)
        elif algo_name == "correlation_test":
            ag_data = correlation_test_route(testFileUrl)
        # 杭州研究院故障诊断算法
        elif algo_name == "fuzzy_safe":
            ag_data = fuzzy_safe_route(testFileUrl)
        elif algo_name == "normal_distribution":
            ag_data = normal_distribution_test_route(testFileUrl)
        else:
            print("该算法不存在，请联系系统管理员进行确认！")
            result = {'ret': 1, 'result': "该算法不存在，请联系系统管理员进行确认！"}
        # ret 返回成功标识
        result = {'ret': 0, 'result': ag_data}
        return json.dumps(result)
# 閮ㄧ讲妯″紡

else:
    if os.path.isfile(config.eval_default_store_list):
        _gb_machinestate = pickle.load(open(config.eval_default_store_list, 'rb'))
    else:
        print("ok")#_gb_machinestate = evalMachineState()


    @app.route('/predictPic', methods=['POST'])
    def predictPic():
        data = request.get_data()
        json_data = json.loads(data.decode("utf-8"))
        result = _gb_machinestate.predict(json_data)
        return json.dumps(result)


    @app.route('/addTask', methods=['POST'])
    def addTask():
        data = json.loads(request.get_data(as_text=True))
        json_data = json.loads(data.decode("utf-8"))
        logging.info("parameter:" + str(json_data))
        result = _gb_machinestate.addTask(json_data)
        pickle.dump(_gb_machinestate, open(config.eval_default_store_list, 'wb'))
        logging.info('result:' + json.dumps(result))
        return json.dumps(result)


    @app.route('/stopTask', methods=['POST'])
    def stopTask():
        data = request.get_data()
        json_data = json.loads(data.decode("utf-8"))
        logging.info("parameter:" + str(json_data))
        result = _gb_machinestate.stopTask(json_data)
        pickle.dump(_gb_machinestate, open(config.eval_default_store_list, 'wb'))
        logging.info('result:' + json.dumps(result))
        return json.dumps(result)


    @app.route('/getTaskList', methods=['POST'])
    def getTaskList():
        result = _gb_machinestate.getTaskList()
        logging.info('result:' + json.dumps(result))
        return json.dumps(result)



if __name__ == '__main__':
    app.run(host='0.0.0.0', port=30004, threaded=2)  #
    # if (config.server_mode == 0):
    #     app.run(host=config.default_ip, port=config.Train_default_port,
    #             threaded=config.default_threaded)  #
    # else:
    #     app.run(host=config.default_ip, port=config.Eval_default_port,
    #             threaded=config.default_threaded)  #


